package xing.appwidget.main

import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.View
import android.widget.PopupWindow
import org.greenrobot.eventbus.EventBus
import xing.appwidget.bean.PackageFilterParam
import xing.appwidget.databinding.PopMainFilterBinding
import xing.appwidget.event.AppFilterUpdateEvent

class MainFilterPopupWindow(activity: Activity) : PopupWindow(activity) {
    private val binding: PopMainFilterBinding

    init {
        binding = PopMainFilterBinding.inflate(LayoutInflater.from(activity))
        contentView = binding.root
        isFocusable = true
        isOutsideTouchable = true
        setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        initBtnClick()
    }

    fun initBtnClick() {
        setBtnClickListener(binding.tvDisabled, binding.tvEnabled)
        setBtnClickListener(binding.tvEnabled, binding.tvDisabled)
        setBtnClickListener(binding.tvSystem, binding.tvUser)
        setBtnClickListener(binding.tvUser, binding.tvSystem)

        binding.tvBtnApply.setOnClickListener {
            with(binding) {
                val filter = PackageFilterParam(tvSystem.isSelected, tvUser.isSelected,
                        tvEnabled.isSelected, tvDisabled.isSelected)
                EventBus.getDefault().post(AppFilterUpdateEvent(filter))
            }
            dismiss()
        }
    }

    fun setData(filter: PackageFilterParam): MainFilterPopupWindow {
        binding.tvDisabled.isSelected = filter.disabled
        binding.tvEnabled.isSelected = filter.enabled
        binding.tvSystem.isSelected = filter.system
        binding.tvUser.isSelected = filter.user
        return this
    }

    fun setBtnClickListener(btn1: View, btn2: View) {
        btn1.setOnClickListener { btn ->
            if (btn.isSelected && !btn2.isSelected) {
                btn2.isSelected = true
            }
            btn.isSelected = !btn.isSelected
        }
    }


}